#include "SSB_uart1.h"
#include "SSB_sys_def.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "esp_log.h"
#include "driver/uart.h"

#include "OPCOL_util.h"

SSB_Uart_callback_fun SSB_callback_fun=NULL;
int SSB_uart_num=UART_NUM_0;

static void SSB_read_uart_task()
{
    uint8_t *data = (uint8_t *) malloc(UART_BUF_SIZE);
    while (1) {
        int len = uart_read_bytes(SSB_uart_num, data, UART_BUF_SIZE, 20 / portTICK_RATE_MS);
        if(len==0){
            continue;
        }

        // char *hex_buf=(char*)malloc(len*3);
        // memset(hex_buf,'\0',len*3);
        // OPCOL_char_array_to_hex((unsigned char *)data,len,hex_buf);
        // ESP_LOGI("TEST","ut:%s",hex_buf);
        // free(hex_buf);

        ESP_LOGI(SSB_TAG,"Received data,len=%d",len);
        // Write data back to the UART
        //uart_write_bytes(UART_NUM_0, (const char *) data, len);
        if(SSB_callback_fun!=NULL){
            SSB_callback_fun((char *)data,len);
        }
    }
    free(data);
}


void SSB_init_uart1(SSB_Uart_callback_fun cf,int baud_rate){
    //115200
    SSB_callback_fun=cf;
    uart_config_t uart_config = {
        .baud_rate = baud_rate,
        .data_bits = UART_DATA_8_BITS,
        .parity    = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE
    };
    
    #ifdef PLATFORM_8266
        SSB_uart_num=UART_NUM_0;
        uart_param_config(SSB_uart_num, &uart_config);
        uart_driver_install(SSB_uart_num, UART_BUF_SIZE*2, 0, 0, NULL);
    #endif

    #ifdef PLATFORM_ESP32
        SSB_uart_num=UART_NUM_1;
        extern int SSB_uart1_tx;
        extern int SSB_uart1_rx;
        uart_param_config(SSB_uart_num, &uart_config);
        uart_set_pin(SSB_uart_num, SSB_uart1_tx, SSB_uart1_rx, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
        uart_driver_install(SSB_uart_num, UART_BUF_SIZE * 2, 0, 0, NULL, 0);
    #endif

    xTaskCreate(SSB_read_uart_task, "SSB_read_uart_task", 1024*6, NULL, 10, NULL);
}

void SSB_uart1_write(char *data,int len){
    uart_write_bytes(SSB_uart_num, data, len);
}